// server.go
package server

import (
	"chatgpt/pkg/handlers"
	"chatgpt/pkg/repository"
	"chatgpt/pkg/service"
	"context"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/sirupsen/logrus"
)

type Server struct {
	httpServer *http.Server
}

func (s *Server) Run(port string, handler http.Handler) error {
	s.httpServer = &http.Server{
		Addr:           ":" + port,
		Handler:        handler,
		MaxHeaderBytes: 1 << 20,
		ReadTimeout:    30 * time.Second,
		WriteTimeout:   10 * time.Second,
	}

	return s.httpServer.ListenAndServe()
}

func (s *Server) Shutdown(ctx context.Context) error {
	return s.httpServer.Shutdown(ctx)
}

func StartServer() {
	logrus.SetFormatter(new(logrus.JSONFormatter))

	repo := repository.NewRepository(os.Getenv("API_KEY"), os.Getenv("API_LINK"), os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PORT"), os.Getenv("PROXY_URL"), os.Getenv("PROXY_USER"), os.Getenv("PROXY_PASSWORD"))
	services := service.NewChatEngine(repo, os.Getenv("MODEL"))
	handlers := handlers.NewChatHandler(services)

	srv := &Server{}
	go func() {
		err := srv.Run(os.Getenv("PORT"), handlers.RegisterRoutes())
		if err != nil {
			logrus.Fatalf("error occured while running http server: %s", err.Error())
		}
	}()
	logrus.Info("Started")

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
	<-quit

	logrus.Info("Shutting Down")

	err := srv.Shutdown(context.Background())
	if err != nil {
		logrus.Errorf("error occured on server shutting down: %s", err.Error())
	}
}
